<template>
  <div class="asset-overview">
    <div class="overview-item total-assets">
      <div class="title">资产总数</div>
      <div class="value">{{ animatedNumbers.totalAssets }}</div>
      <div class="indicators">
        <div class="indicator">
          <span>空置率</span>
          <!-- <el-icon><CaretTop /></el-icon> -->
          <span>{{ data.vacantRate }}</span>
        </div>
        <div class="indicator">
          <span>空置总数</span>
          <!-- <el-icon><CaretBottom /></el-icon> -->
          <span>{{ animatedNumbers.vacantTotal }}</span>
        </div>
      </div>
    </div>
    <div class="overview-item rental">
      <div class="title">租金价格预警数</div>
      <div
        class="value clickable"
        @click="goToAssetList('rental', animatedNumbers.rentalPriceCount)"
      >
        {{ animatedNumbers.rentalPriceCount }}
      </div>
      <div class="chart" ref="rentalPriceChart"></div>
    </div>
    <div class="overview-item contract">
      <div class="title">合同合规预警数</div>
      <div
        class="value clickable"
        @click="goToAssetList('contract', animatedNumbers.contractCount)"
      >
        {{ animatedNumbers.contractCount }}
      </div>
      <div class="chart" ref="contractChart"></div>
    </div>
    <div class="overview-item vacancy">
      <div class="title">空置监测预警数</div>
      <div
        class="value clickable"
        @click="goToAssetList('vacancy', animatedNumbers.emptyMonitorCount)"
      >
        {{ animatedNumbers.emptyMonitorCount }}
      </div>
      <div class="chart" ref="emptyMonitorChart"></div>
    </div>
    <div class="overview-item no-contract">
      <div class="title">无合同率</div>
      <div
        class="value clickable"
        @click="goToAssetList('noContract', data.noContractRate)"
      >
        {{ data.noContractRate }}
      </div>
      <div class="progress-wrapper">
        <el-tooltip
          :content="`无合同率: ${data.noContractRate}`"
          placement="top"
          effect="light"
        >
          <div class="progress-bar">
            <div class="progress" :style="{ width: data.noContractRate }"></div>
          </div>
        </el-tooltip>
      </div>
    </div>
  </div>
</template>

<script setup>
import { CaretTop, CaretBottom } from "@element-plus/icons-vue";
import { ref, onMounted, watch, computed, nextTick, onUnmounted } from "vue";
import * as echarts from "echarts";
import { useRouter } from "vue-router";

const props = defineProps({
  data: {
    type: Object,
    required: true,
    default: () => ({
      totalAssets: 0,
      vacantRate: "0%",
      rentalPriceCount: 0,
      contractCount: 0,
      emptyMonitorCount: 0,
      noContractRate: "0%",
      vacantTotal: 0,
    }),
  },
  // 添加三个图表数据的props
  rentalData: {
    type: Array,
    default: () => [],
  },
  contractData: {
    type: Array,
    default: () => [],
  },
  vacancyData: {
    type: Array,
    default: () => [],
  },
});

const router = useRouter();

// 动画数字对象
const animatedNumbers = ref({
  totalAssets: 0,
  vacantTotal: 0,
  rentalPriceCount: 0,
  contractCount: 0,
  emptyMonitorCount: 0,
});

// 处理图表数据
const chartData = computed(() => {
  // 获取最近12个月的数据
  const getRecentData = (data) => {
    if (!data || !data.length) return [];
    // 按日期排序
    const sortedData = [...data].sort((a, b) => a.date.localeCompare(b.date));
    // 取最近12个月
    return sortedData.slice(-12);
  };

  return {
    rental: getRecentData(props.rentalData),
    contract: getRecentData(props.contractData),
    vacancy: getRecentData(props.vacancyData),
  };
});

// 动画函数
const animateNumber = (start, end, duration = 1000, key) => {
  const startTime = Date.now();
  const difference = end - start;

  const animate = () => {
    const currentTime = Date.now();
    const elapsed = currentTime - startTime;

    if (elapsed > duration) {
      animatedNumbers.value[key] = end;
      return;
    }

    const progress = elapsed / duration;
    const currentValue = Math.round(start + difference * progress);
    animatedNumbers.value[key] = currentValue;

    requestAnimationFrame(animate);
  };

  animate();
};

// 更新所有数字的动画
const updateNumbers = (newData) => {
  const keys = [
    "totalAssets",
    "vacantTotal",
    "rentalPriceCount",
    "contractCount",
    "emptyMonitorCount",
  ];
  keys.forEach((key) => {
    const targetValue = Number(newData[key]) || 0;
    animateNumber(animatedNumbers.value[key], targetValue, 1000, key);
  });
};

// 添加图表相关的ref
const rentalPriceChart = ref(null);
const contractChart = ref(null);
const emptyMonitorChart = ref(null);

// 监听数据变化
watch(
  () => props.data,
  (newData) => {
    console.log("数据更新:", newData);
    if (!newData) {
      const defaultData = {
        totalAssets: 0,
        vacantTotal: 0,
        rentalPriceCount: 0,
        contractCount: 0,
        emptyMonitorCount: 0,
        warningData: [],
      };
      updateNumbers(defaultData);
      return;
    }
    updateNumbers(newData);
    // 确保在下一个 tick 初始化图表，避免 DOM 未更新
    nextTick(() => {
      initCharts();
    });
  },
  { deep: true, immediate: true }
);

// 组件挂载时初始化
onMounted(() => {
  console.log("组件挂载，当前数据:", props.data);
  nextTick(() => {
    initCharts();
  });
});

// 组件卸载时清理图表实例
onUnmounted(() => {
  const charts = [
    rentalPriceChart.value,
    contractChart.value,
    emptyMonitorChart.value,
  ];
  charts.forEach((chart) => {
    if (chart) {
      chart.dispose();
    }
  });
});

function initCharts() {
  initRentalPriceChart();
  initContractChart();
  initEmptyMonitorChart();
}

// 初始化租金价格图表
const initRentalPriceChart = () => {
  if (!rentalPriceChart.value) return;

  const chart = echarts.init(rentalPriceChart.value);
  const rentalData = chartData.value.rental;

  // 获取主题色变量
  const primaryColor =
    getComputedStyle(document.documentElement).getPropertyValue(
      "--el-color-primary"
    ) || "#60A5FA";

  const option = {
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(255, 255, 255, 0.9)",
      borderColor: "#e6e6e6",
      borderWidth: 1,
      padding: [5, 10],
      textStyle: {
        color: "#666",
        fontSize: 12,
      },
      formatter: (params) => {
        const data = params[0];
        const item = rentalData[params[0].dataIndex];
        return `${item.date}<br/>${data.marker}租金价格预警：${data.value}个`;
      },
      axisPointer: {
        type: "none",
      },
    },
    grid: {
      left: 0,
      right: 0,
      top: 5,
      bottom: 0,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      show: false,
      data: rentalData.map((item) => {
        const [year, month] = item.date.split("-");
        return `${month}月`;
      }),
    },
    yAxis: {
      type: "value",
      show: false,
    },
    series: [
      {
        data: rentalData.map((item) => item.count),
        type: "line",
        smooth: true,
        showSymbol: false,
        symbol: "circle",
        symbolSize: 6,
        emphasis: {
          scale: true,
          focus: "series",
          itemStyle: {
            color: primaryColor.trim(),
            borderColor: "#fff",
            borderWidth: 2,
            shadowBlur: 5,
            shadowColor: "rgba(0,0,0,0.2)",
          },
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: primaryColor.trim() + "4D", // 30% 透明度
              },
              {
                offset: 1,
                color: primaryColor.trim() + "0D", // 5% 透明度
              },
            ],
          },
        },
        lineStyle: {
          width: 2,
          color: primaryColor.trim(),
        },
        itemStyle: {
          color: primaryColor.trim(),
          borderWidth: 0,
        },
      },
    ],
  };

  chart.setOption(option);
  window.addEventListener("resize", () => {
    chart.resize();
  });
};

// 初始化合同合规图表
const initContractChart = () => {
  if (!contractChart.value) return;

  const chart = echarts.init(contractChart.value);
  const contractData = chartData.value.contract;

  const contractColor = "#22C55E";

  const option = {
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(255, 255, 255, 0.9)",
      borderColor: "#e6e6e6",
      borderWidth: 1,
      padding: [5, 10],
      textStyle: {
        color: "#666",
        fontSize: 12,
      },
      formatter: (params) => {
        const data = params[0];
        const item = contractData[params[0].dataIndex];
        return `${item.date}<br/>${data.marker}合同合规预警：${data.value}个`;
      },
      axisPointer: {
        type: "none",
      },
    },
    grid: {
      left: 0,
      right: 0,
      top: 5,
      bottom: 0,
      containLabel: false,
    },
    xAxis: {
      type: "category",
      data: contractData.map((item) => {
        const [year, month] = item.date.split("-");
        return `${month}月`;
      }),
      show: false,
    },
    yAxis: {
      type: "value",
      show: false,
    },
    series: [
      {
        data: contractData.map((item) => item.count),
        type: "bar",
        barWidth: "60%",
        itemStyle: {
          color: contractColor,
          borderRadius: [2, 2, 0, 0],
        },
      },
    ],
  };

  chart.setOption(option);
  window.addEventListener("resize", () => {
    chart.resize();
  });
};

// 初始化空置监测图表
const initEmptyMonitorChart = () => {
  if (!emptyMonitorChart.value) return;

  const chart = echarts.init(emptyMonitorChart.value);
  const vacancyData = chartData.value.vacancy;

  const vacancyColor = "#F59E42";

  const option = {
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(255, 255, 255, 0.9)",
      borderColor: "#e6e6e6",
      borderWidth: 1,
      padding: [5, 10],
      textStyle: {
        color: "#666",
        fontSize: 12,
      },
      formatter: (params) => {
        const data = params[0];
        const item = vacancyData[params[0].dataIndex];
        return `${item.date}<br/>${data.marker}空置监测预警：${data.value}个`;
      },
      axisPointer: {
        type: "none",
      },
    },
    grid: {
      left: 0,
      right: 0,
      top: 5,
      bottom: 0,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      show: false,
      data: vacancyData.map((item) => {
        const [year, month] = item.date.split("-");
        return `${month}月`;
      }),
    },
    yAxis: {
      type: "value",
      show: false,
    },
    series: [
      {
        data: vacancyData.map((item) => item.count),
        type: "line",
        smooth: true,
        showSymbol: vacancyData.length === 1 ? true : false,
        symbol: "circle",
        symbolSize: 6,
        emphasis: {
          scale: true,
          focus: "series",
          itemStyle: {
            color: vacancyColor,
            borderColor: "#fff",
            borderWidth: 4,
            shadowBlur: 5,
            shadowColor: "rgba(0,0,0,0.2)",
          },
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: vacancyColor + "4D",
              },
              {
                offset: 1,
                color: vacancyColor + "0D",
              },
            ],
          },
        },
        lineStyle: {
          width: 4,
          color: vacancyColor,
        },
        itemStyle: {
          color: vacancyColor,
          borderWidth: 0,
        },
      },
    ],
  };

  chart.setOption(option);
  window.addEventListener("resize", () => {
    chart.resize();
  });
};

function goToAssetList(type) {
  // type 可能为 contract/price/vacancy/noContract
  const typeMap = {
    contract: "合同合规",
    rental: "价格对比",
    vacancy: "空置",
    noContract: "无合同",
  };
  router.push({
    path: "/assetList",
    query: { warningType: typeMap[type] },
  });
}
</script>

<style lang="scss" scoped>
.asset-overview {
  display: flex;
  gap: 12px;
  margin-bottom: 0;

  .overview-item {
    flex: 1;
    background: #fff;
    padding: 16px;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    display: flex;
    flex-direction: column;
    min-height: 120px;

    .title {
      color: #909399;
      font-size: 13px;
      margin-bottom: 8px;
      font-weight: 400;
    }

    .value {
      font-size: 28px;
      font-weight: 600;
      color: #1f2937;
      line-height: 1;
      margin-bottom: 8px;
    }

    .value.clickable {
      cursor: pointer;
      color: #409eff;
      transition: color 0.2s;
      &:hover {
        color: #1a73e8;
      }
    }

    .indicators {
      display: flex;
      gap: 16px;
      font-size: 12px;
      margin-top: auto;
      padding-top: 4px;

      .indicator {
        display: flex;
        align-items: center;
        gap: 4px;

        .el-icon {
          font-size: 12px;
        }

        &.up {
          color: #67c23a;
          .el-icon {
            color: #67c23a;
          }
        }

        &.down {
          color: #f56c6c;
          .el-icon {
            color: #f56c6c;
          }
        }
      }
    }

    .progress-wrapper {
      margin-top: auto;
      padding-top: 20px;

      .progress-bar {
        width: 100%;
        height: 12px;
        background: #f3f4f6;
        border-radius: 5px;
        overflow: hidden;
        margin-bottom: 3px;
        .progress {
          height: 100%;
          background: #60a5fa;
          border-radius: 5px;
          transition: width 0.3s ease;
        }
      }
    }

    .chart {
      height: 36px;
      margin-top: auto;
    }
  }

  // 主题色（租金价格预警数）
  .overview-item.rental {
    .chart {
      color: var(--el-color-primary);
    }
    .progress-bar .progress {
      background: var(--el-color-primary);
    }
  }
  // 合同合规预警数
  .overview-item.contract {
    .chart {
      color: #22c55e;
    }
    .progress-bar .progress {
      background: #22c55e;
    }
  }
  // 空置监测预警数
  .overview-item.vacancy {
    .chart {
      color: #f59e42;
    }
    .progress-bar .progress {
      background: #f59e42;
    }
  }
  // 无合同率
  .overview-item.no-contract {
    .chart {
      color: #f87171;
    }
    .progress-bar .progress {
      background: #f87171;
    }
  }
}
</style>
